package com.zero.consul.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.LinkedList;
import java.util.List;

@RestController
public class DiscoveryClientController {


    private final DiscoveryClient discoveryClient;

    private final String currentApplicationName;

    @Autowired
    public DiscoveryClientController(DiscoveryClient discoveryClient,
                                     @Value("spring.application.name") String currentApplicationName) {
        this.discoveryClient = discoveryClient;
        this.currentApplicationName = currentApplicationName;
    }

    /**
     * 获取所有的服务
     * @return
     */
    @GetMapping("/list/services")
    private List<String> getServices(){
        return discoveryClient.getServices();
    }

    /**
     * 获取所有的实例
     * @return
     */
    @GetMapping("/list/instances")
    private List<ServiceInstance> getInstances(){
        List<String> services = getServices();
        LinkedList<ServiceInstance> instances = new LinkedList<>();
        services.forEach(serviceName ->{
            instances.addAll(discoveryClient.getInstances(serviceName));
        });

        return instances;
    }

    /**
     * 获取当前实例
     * @return
     */
    @GetMapping("/list/currentInstance")
    public ServiceInstance getCurrentInstance(){
            return discoveryClient.getInstances(currentApplicationName).get(0);
    }
}
